package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.SetLineMapper;
import com.ruoyi.system.mapper.SetProductMapper;
import com.ruoyi.system.mapper.SetStationMapper;
import com.ruoyi.system.mapper.SetStepMapper;
import com.ruoyi.system.service.ISetStepService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 操作步骤Service业务层处理
 * 
 * @author ruoyi
 * @date 2022-11-21
 */
@Service
public class SetStepServiceImpl implements ISetStepService
{
    private static final Logger log = LoggerFactory.getLogger(SetStepServiceImpl.class);

    @Autowired
    private SetStepMapper setStepMapper;

    @Autowired
    private SetLineMapper setLineMapper;

    @Autowired
    private SetProductMapper setProductMapper;

    @Autowired
    private SetStationMapper setStationMapper;

    /**
     * 查询操作步骤
     * 
     * @param id 操作步骤主键
     * @return 操作步骤
     */
    @Override
    public SetStep selectSetStepById(Long id)
    {
        return setStepMapper.selectSetStepById(id);
    }

    /**
     * 查询操作步骤
     *
     * @param productCode 总成编码
     * @param lineCode 产线编码
     * @param stationCode 工位编码
     * @return 操作步骤
     */
    public SetStep selectSetStepByCode(String productCode,String lineCode,String stationCode)
    {
        return setStepMapper.selectSetStepByCode( productCode, lineCode, stationCode);
    }

    /**
     * 查询操作步骤列表
     * 
     * @param setStep 操作步骤
     * @return 操作步骤
     */
    @Override
    public List<SetStep> selectSetStepList(SetStep setStep)
    {
        return setStepMapper.selectSetStepList(setStep);
    }

    /**
     * 新增操作步骤
     * 
     * @param setStep 操作步骤
     * @return 结果
     */
    @Override
    @Transactional
    public int insertSetStep(SetStep setStep)
    {
        setStep.setCreateTime(DateUtils.getNowDate());
        setStep.setCreateBy(SecurityUtils.getUsername());
        setStep.setStatus(UserConstants.NORMAL);
        return setStepMapper.insertSetStep(setStep);
    }

    /**
     * 修改操作步骤
     * 
     * @param setStep 操作步骤
     * @return 结果
     */
    @Override
    @Transactional
    public int updateSetStep(SetStep setStep)
    {
        setStep.setUpdateTime(DateUtils.getNowDate());
        setStep.setUpdateBy(SecurityUtils.getUsername());
        return setStepMapper.updateSetStep(setStep);
    }

    /**
     * 批量删除操作步骤
     *
     * @param ids 需要删除的操作步骤主键
     * @return 结果
     */
    @Override
    public int deleteSetStepByIds(Long[] ids) {
        return setStepMapper.deleteSetStepByIds(ids);
    }

    /**
     * 删除操作步骤信息
     * 
     * @param id 操作步骤主键
     * @return 结果
     */
    @Override
    public int deleteSetStepById(Long id)
    {
        return setStepMapper.deleteSetStepById(id);
    }

    /**
     * 导入操作步骤数据
     *
     * @param stepList 操作步骤数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importStep(List<SetStep> stepList, boolean isUpdateSupport, String operName) {

        if (StringUtils.isNull(stepList) || stepList.size() == 0)
        {
            throw new CustomException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        //String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SetStep setStep : stepList)
        {
            try
            {
                // 验证是否存在这个操作步骤
                SetStep ss = setStepMapper.selectSetStepByCode(setStep.getProductCode(),setStep.getLineCode(),setStep.getStationCode());

                if (StringUtils.isNull(ss))
                {
                    SetLine sl = setLineMapper.selectSetLineByLineCode(setStep.getLineCode());
                    SetStation ssn = setStationMapper.selectSetStationByCode(setStep.getStationCode());
                    SetProduct sp = setProductMapper.selectSetProductByCode(setStep.getProductCode());
                    if(StringUtils.isNull(sl) || StringUtils.isNull(ssn) || StringUtils.isNull(sp)){
                        failureNum++;
                        failureMsg.append("<br/>" + failureNum + "、产线编码-工位编码-总成编码： " + ((sl == null)?null:sl.getLineCode()) + "-" + ((ssn == null)?null:ssn.getStationCode()) + "-" + ((sp == null)?null:sp.getProductCode()) + " 在数据库中不存在");
                    }else{
                        setStep.setCreateBy(operName);
                        this.insertSetStep(setStep);
                        successNum++;
                        successMsg.append("<br/>" + successNum + "、操作步骤 " + setStep.getStepName() + " 导入成功");
                    }
                }
                else if (isUpdateSupport)
                {
                    setStep.setUpdateBy(operName);
                    this.updateSetStep(setStep);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、操作步骤 " + setStep.getStepName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、操作步骤 " + setStep.getStepName() + " 已存在");
                }

            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、操作步骤 " + setStep.getStepName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 校验步骤名称是否唯一
     *
     * @param setStep 步骤信息
     * @return 结果
     */
    @Override
    public String checkNameUnique(SetStep setStep)
    {
        Long id = StringUtils.isNull(setStep.getId()) ? -1L : setStep.getId();
        SetStep info = setStepMapper.checkNameUnique(setStep.getStepName());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != id.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
